package com.tinyideatech.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.tinyideatech.common.utils.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class HttpClientUtil {

    public static final String CHARSET_UTF_8 = "utf-8";

    public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";

    public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    /**
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 200;

    /**
     * 返回失败状态码
     */
    private static final int BAD_CODE = 400;

    /**
     * 发送GET请求
     *
     * @param url               请求url
     * @param nameValuePairList 请求参数
     * @return JSON或者字符串
     * @throws Exception
     */
    public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
        JSONObject jsonObject = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            /**
             * 创建HttpClient对象
             */
            client = HttpClients.createDefault();
            /**
             * 创建URIBuilder
             */
            URIBuilder uriBuilder = new URIBuilder(url);
            /**
             * 设置参数
             */
            uriBuilder.addParameters(nameValuePairList);
            /**
             * 创建HttpGet
             */
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            /**
             * 设置请求头部编码
             */
            httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            /**
             * 设置返回编码
             */
            httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
            /**
             * 请求服务
             */
            response = client.execute(httpGet);
            /**
             * 获取响应吗
             */
            int statusCode = response.getStatusLine().getStatusCode();

            if (SUCCESS_CODE == statusCode) {
                /**
                 * 获取返回对象
                 */
                HttpEntity entity = response.getEntity();
                /**
                 * 通过EntityUitls获取返回内容
                 */
                String result = EntityUtils.toString(entity, "UTF-8");
                /**
                 * 转换成json,根据合法性返回json或者字符串
                 */
                try {
                    jsonObject = JSONObject.parseObject(result);
                    return jsonObject;
                } catch (Exception e) {
                    return result;
                }
            } else {
                LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败！");
            }
        } catch (Exception e) {
            LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
        } finally {
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param nameValuePairList
     * @return JSON或者字符串
     * @throws Exception
     */
    public static JSONObject sendPost(String url, List<NameValuePair> nameValuePairList, String token) throws Exception {
        JSONObject jsonObject = new JSONObject();
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        HttpEntity httpEntity = null;
        try {

            client = HttpClients.createDefault();

            HttpPost post = new HttpPost(url);

            StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");

            post.setEntity(entity);

            post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

            if (StringUtils.isNotNull(token)) {
                post.setHeader(new BasicHeader("Authorization", "Bearer." + token));
            }

            post.setHeader(new BasicHeader("Accept", "*/*"));
            for (Header header : post.getAllHeaders()) {
                System.out.println(header);
            }
            response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            if (SUCCESS_CODE == statusCode) {
                jsonObject.put("status", statusCode);
                jsonObject.put("entity", result);
                return jsonObject;
//                try {result.split("。")
//                    if (JSON.isJson(result)) {
//                        jsonObject = JSONObject.parseObject(result);
//                        LOGGER.info(String.format("result is JSON [%s]", jsonObject));
//                        return jsonObject;
//                    } else {
//                        jsonObject.put("result", result);
//                        LOGGER.info(String.format("result is NOT JSON [%s]", jsonObject));
//                        return jsonObject;
//                    }
//                } catch (Exception e) {
//                    e.getStackTrace();
//                }
            } else if (BAD_CODE == statusCode) {
                jsonObject.put("status", BAD_CODE);
                jsonObject.put("entity", result);
                return jsonObject;
            } else {
                jsonObject.put("status", statusCode);
                LOGGER.error("HttpClientService-line: {}, errorMsg：{}", 146, "POST请求失败！, 请求代码status:" + statusCode);
                return jsonObject;
            }
        } catch (Exception e) {
            LOGGER.error("HttpClientService-line: {}, Exception：{}", 149, e);

        } finally {
            EntityUtils.consume(httpEntity);
            response.close();
            client.close();
        }
        jsonObject.put("status", "500");
        return jsonObject;
    }

    /**
     * 组织请求参数{参数名和参数值下标保持一致}
     *
     * @param params 参数名数组
     * @return 参数对象
     */
    public static List<NameValuePair> getParams(Map<String, String> params) {
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        Set<String> keys = params.keySet();
        for (String key : keys) {
            nameValuePairList.add(new BasicNameValuePair(key, params.get(key)));
        }
        return nameValuePairList;
    }

    /**
     * 获取客户端请求参数中所有的信息
     *
     * @param request
     * @return
     */
    private Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) throws Exception {

        String url = "http://47.104.142.111:8081/password/change";
        Map<String, String> params = new HashMap<>();
        params.put("oldPassword", "");
        params.put("newPassword", "yao12345");

//        params.put("code", "999999");
        List<NameValuePair> paramsList = HttpClientUtil.getParams(params);
//        Object result = HttpClientUtil.sendGet(url, paramsList);
        Object result2 = HttpClientUtil.sendPost(url, paramsList, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsInRpbWUiOiIyMDE5LTEyLTMxIDA4OjI5OjEyIn0.eyJwcmluY2lwYWwiOiIxNTAxMDQ0MjczNyJ9.LkYDwJ-llZvejfk1KUy6aJxpNWYJV8SbusrKwN3KfXY");
        System.out.println("POST返回信息：" + result2);
    }

}
